import React, { useState, useEffect, useCallback, useRef } from 'react';
import { getNewsList as getNewsListData } from '../../../service';
import { List, Empty } from 'antd';
import NewsItem from './newsItem';
import { useEvents } from '@inbiz/utils';
import { TextWidget } from '@inbiz/react';

const NewsRollListView: React.FC<any> = (props) => {
  const { delay = 2, pageSize, fixNewKey, standOut } = props;
  // 列表每一项的高度
  const itemHeight = 42;
  const prefixCls = 'inbiz-News_roll_list';
  // 列表数据
  const [dataList, $dataList] = useState<Array<News.NewsItem>>([]);
  // 记录总数
  const [total, $total] = useState(0);
  // 滚动容器高度
  const [height, $height] = useState(0);
  // 位移像素值
  const [transformY, $transformY] = useState<number>(0);
  // 是否初始化过
  const [isInit, $init] = useState(false);
  // 当前节点
  const nowIdx = useRef(0);
  // 滚动容器Div Dom
  const scrollRef = useRef<any>();
  // 定时器对象
  const timer = useRef<any>();

  const [configEvents] = useEvents(props.callBackEvents, props.emit)
  const getNewsList = useCallback(async (params: object) => {
    const newParams = (await configEvents.current?.onParams?.(params)) || params;
    const data = await (configEvents.current?.onRequest || getNewsListData)(newParams as any)
    return await configEvents.current?.onData?.(data) || data
  }, []);

  // 触发获取列表数据
  useEffect(() => {
    $dataList([]);
    getList(1, (list: any[]) => {
      let arr = list ? [...list] : [];
      if (arr.length > pageSize) {
        arr = [...arr, ...arr.slice(0, pageSize)];
      }
      $dataList(arr || []);
      $init(true)
    });
  }, [fixNewKey, pageSize]);

  // 计算滚动容器高度
  useEffect(() => {
    if (total < pageSize) {
      $height(itemHeight * total);
    } else {
      $height(itemHeight * pageSize);
    }
  }, [pageSize, total]);

  // 开启滚动
  useEffect(() => {
    $transformY(0);
    nowIdx.current = 0;
    if (total > pageSize) {
      openInterval(total);
    }
    return () => clearInterval(timer.current);
  }, [total, pageSize]);

  // 打开定时器
  const openInterval = useCallback((total: number) => {
    timer.current = setInterval(() => {
      nowIdx.current = nowIdx.current + 1;
      $transformY(nowIdx.current * itemHeight);
      if (nowIdx.current === total) {
        let timeOut = setTimeout(() => {
          nowIdx.current = 0;
          scrollRef.current.style.transitionDuration = '0s';
          scrollRef.current.style.transform = 'translateY(0px)';
          let timeOut2 = setTimeout(() => {
            scrollRef.current.style.transitionDuration = '0.5s';
            clearTimeout(timeOut2);
          }, 300);
          clearTimeout(timeOut);
        }, 550);
      }
    }, delay * 1000);
  }, []);

  // 获取列表数据
  const getList = async (page: number, callback: Function) => {
    const res: News.NewsList = await getNewsList({
      categoryId: fixNewKey?.map((item: any) => { return item.id }).toString(),
      pageIndex: page,
      pageSize: 999999,
      showNew: standOut?.isStandout,
      numNew: standOut?.threshold || undefined,
    });
    $total(res.Total || 0);
    callback(res.ContentList || []);
  };
  console.log('>>> LL', dataList.length, fixNewKey.length && !isInit);
  
  return (
    <List
      locale={{
        emptyText: <Empty
          image={null}
          description={''}
        />,
      }}
    >
      {dataList.length > 0 ? <div
        className={`${prefixCls} eform-new-list`}
        style={{ height }}
        onMouseLeave={() => { if (total > pageSize) openInterval(total) }}
        onMouseEnter={() => clearInterval(timer.current)}
      >
        <div
          ref={scrollRef}
          className={`${prefixCls}_content`}
          style={{ transform: `translateY(-${transformY}px)` }}
        >
          {dataList.map((item: any, idx: number) => (
            <NewsItem key={item.ID + idx} {...props} {...item} viewType="roll" />
          ))}
        </div>
      </div> :
      fixNewKey.length && !isInit ? null :
        <div style={{ padding: '16px' }}>
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={<TextWidget>News.noData</TextWidget>}
          />
        </div>
      }
    </List>
  );
};

export default NewsRollListView;
